package ws

import (
	"encoding/json"
	socketio "github.com/googollee/go-socket.io"
	"iot-base/auth/api/logic"
	"iot-base/auth/common/socket"
	"iot-base/auth/config"
	types2 "iot-base/auth/types"
)

// SubscribeAlarm 订阅告警.
func SubscribeAlarm(s socketio.Conn, msg string) {
	resp := types2.NewSocketIoResult()
	if msg == "" {
		s.Emit(config.EventSubscribeAlarm, resp.ErrorCode(types2.ParamsError, "", ""))
		return
	}
	req := &types2.ReqSubscribeAlarm{}
	err := json.Unmarshal([]byte(msg), req)
	if err != nil {
		s.Emit(config.EventSubscribeAlarm, resp.ErrorCode(types2.ParamsError, "", ""))
		return
	}
	conn, err := socket.StoreSocketIo.Get(s.ID())
	if err != nil {
		s.Emit(config.EventSubscribeAlarm, resp.ErrorCode(types2.SubscribeErr, "", ""))
		return
	}
	socket.Sub.SubStationMsg(conn.Uid, req.StationId)
	result, _ := logic.NewAlarmLogic().GetStationAlarm(req.StationId)
	s.Emit(config.EventSubscribeAlarm, resp.Success(result, ""))
	return
}

// UnsubscribeAlarm 取消订阅.
func UnsubscribeAlarm(s socketio.Conn, msg string) {
	resp := types2.NewSocketIoResult()
	if msg == "" {
		s.Emit(config.EventUnSubscribeAlarm, resp.ErrorCode(types2.ParamsError, "", ""))
		return
	}
	req := &types2.ReqSubscribeAlarm{}
	err := json.Unmarshal([]byte(msg), req)
	if err != nil {
		s.Emit(config.EventUnSubscribeAlarm, resp.ErrorCode(types2.ParamsError, "", ""))
		return
	}
	conn, err := socket.StoreSocketIo.Get(s.ID())
	if err != nil {
		s.Emit(config.EventUnSubscribeAlarm, resp.ErrorCode(types2.SubscribeErr, "", ""))
		return
	}
	socket.Sub.UnSubStationMsg(conn.Uid, req.StationId)
}
